//
//  SkinTool.m
//
//
//  Created by lxf on 15/7/12.
//  Copyright (c) 2015年 lxf. All rights reserved.
//

#import "SkinTool.h"
#import "UIColor+customHEX.h"


@interface SkinTool()

@end
static NSString *_skin;
@implementation SkinTool

/**
 *  类加载的时候 就会调用  调用一次
 */
+(void)initialize
{
    _skin = [[NSUserDefaults standardUserDefaults]objectForKey:@"SkinTool.skin"];
    if (_skin == nil) {
        _skin = [self defaultSkin];
    }
}

+(NSString *)defaultSkin{
    return @"skin/default";
}

/**
 *  类方法
 */
+ (void)saveSkin:(NSString *)skin
{
    _skin = skin;
    //保存
    [[NSUserDefaults standardUserDefaults]setObject:skin forKey:@"SkinTool.skin"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
}

+(NSString *)currentlySkin{
    return _skin;
}

+ (UIImage *)loadImage:(NSString *)imageName{
    UIImage *image = [self loadImage:imageName skin:[self currentlySkin]];
    if (image) {
        return image;
    }
    
    image = [self loadImageByLocal:imageName];
    if (image) {
        return image;
    }
    
    image = [self loadImage:imageName skin:[self defaultSkin]];
    return image;
}

+(UIImage *)loadImageByLocal:(NSString *)imageName{
    UIImage *image = [self loadImageByLocal:imageName skin:[self currentlySkin]];
    if (image) {
        return image;
    }
    image = [self loadImageByLocal:imageName skin:[self defaultSkin]];
    return image;
}

+ (UIColor *)loadColor:(NSString *)key{
    UIColor *color = [self loadColor:key skin:[self currentlySkin]];
    if (color) {
        return color;
    }
    
    color = [self loadColor:key skin:[self defaultSkin]];
    
    return color;
}

#pragma mark - 私有方法
+(UIImage *)loadImage:(NSString *)imageName  skin:(NSString *)skin
{
    NSString *pathName = [NSString stringWithFormat:@"%@/%@",skin,imageName];
    UIImage *image = [UIImage imageNamed:pathName];
    
    return image;
}

+(UIImage *)loadImageByLocal:(NSString *)imageName skin:(NSString *)skin
{
    NSString *pathName = [NSString stringWithFormat:@"%@/%@",skin,imageName];
    NSString *path = [[NSBundle mainBundle]pathForResource:pathName ofType:@""];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    
    return image;
}

+(UIColor *)loadColor:(NSString *)key skin:(NSString *)skin
{
    //拼接
    NSString *plistName = [NSString stringWithFormat:@"%@/color.plist",skin];
    NSString *path = [[NSBundle mainBundle]pathForResource:plistName ofType:nil];
    
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
    
    NSString *result = dict[key];
    
    NSArray *allColor = [result componentsSeparatedByString:@","];
    
    CGFloat alpha = [allColor[0] doubleValue]/100;
    NSString *hex = allColor[1];
    
    return [UIColor colorWithHexString:hex alpha:alpha];
    
}


@end
